﻿using Microsoft.Practices.Unity;
using StockholmsStad.Windows.UI.Infrastructure.Interfaces;
using StockholmsStad.Windows.UI.Modules.Couple.Interfaces;
using StockholmsStad.Windows.UI.Modules.Couple.Models;
using StockholmsStad.Windows.UI.Facade;
using StockholmsStad.Runtime.Serialization.DataContract;

namespace StockholmsStad.Windows.UI.Modules.Couple.Services
{
    public class ExtrasService : IExtrasService
    {
        private IApplicationService applicationService;

        [Dependency]
        public IApplicationService ApplicationService
        {
            set { applicationService = value; }
        }

        public ExtrasPresentationModel GetExtras(int ticketId)
        {
            var model = new ExtrasPresentationModel();

            if(ticketId > 0)
            {
                var user = applicationService.GetCurrentUser();
                TicketInformation ticketInfo = new TicketFacade(user).GetTicketInformation(ticketId);

                if (ticketInfo != null)
                    model.ExtrasInfo = ticketInfo.InformationText;
            }

            model.TicketId = ticketId;
            model.Saved += model_Saved;
            return model;
        }

        private void model_Saved(object sender, Microsoft.Practices.Composite.Events.DataEventArgs<ExtrasPresentationModel> e)
        {
            if (e != null && e.Value != null)
            {
                ExtrasPresentationModel model = e.Value;

                if (model.TicketId.HasValue)
                {
                    var ticketInfo = new TicketInformation
                                         {
                                             TicketId = model.TicketId.Value,
                                             InformationText = model.ExtrasInfo
                                         };

                    var user = applicationService.GetCurrentUser();
                    var facade = new TicketFacade(user);

                    facade.UpdateTicketInformation(ticketInfo);
                }
            }
        }
    }
}
